#include "MySetting.h"

MySetting::MySetting(void)
{
    int esize = sizeof(CalibratePoint) * SENSER_QUANTITY;
    if (!EEPROM.begin(esize)) //0~4096 初始化大小
    {
        Serial.println("Failed to initialise EEPROM");
        Serial.println("Restarting...");
        delay(1000);
        ESP.restart();
    }
    readAll();
}

MySetting::~MySetting()
{
}

CalibratePoint *MySetting::readAll()
{
    for (size_t i = 0; i < SENSER_QUANTITY; i++)
    {
        int address = sizeof(CalibratePoint) * i;

        // uint8_t *p = (uint8_t *)(&calibratePoint[i]);

        // for (int i = 0; i < sizeof(CalibratePoint); i++)
        // {
        //     *(p + i) = EEPROM.read(i + address);
        // }

        for (size_t j = 0; j < CALIBRATE_POINT_MAX; j++)
        {
            calibratePoint[i].raw[j] = EEPROM.readUInt(address);
            address += sizeof(uint16_t);

            calibratePoint[i].t[j] = EEPROM.readDouble(address);
            address += sizeof(double);
        }

        for (size_t k = 0; k < CALIBRATE_RANK + 1; k++)
        {
            calibratePoint[i].parameter[k] = EEPROM.readDouble(address);
            address += sizeof(double);
        }
    }
    return this->calibratePoint;
}

void MySetting::writeAll()
{
    for (size_t i = 0; i < SENSER_QUANTITY; i++)
    {

        int address = sizeof(CalibratePoint) * i;

        // uint8_t *p = (uint8_t *)(&calibratePoint[i]);

        // for (int i = 0; i < sizeof(CalibratePoint); i++)
        // {
        //     EEPROM.write(i + address, *(p + i));
        // }

        for (size_t j = 0; j < CALIBRATE_POINT_MAX; j++)
        {
            EEPROM.writeUInt(address, this->calibratePoint[i].raw[j]);
            address += sizeof(uint16_t);

            EEPROM.writeDouble(address, this->calibratePoint[i].t[j]);
            address += sizeof(double);
        }

        for (size_t k = 0; k < CALIBRATE_RANK + 1; k++)
        {
            EEPROM.writeDouble(address, this->calibratePoint[i].parameter[k]);
            address += sizeof(double);
        }
    }
    EEPROM.commit(); //等待写入完成
}